/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component, Fragment} from 'react';
import {
  Form,
  Button,
  Badge,
  Typography,
  Tooltip,
  DatePicker,
  Descriptions,
  Input,
  Icon as AIcon,
  Drawer,
  message, Tabs,
  Modal, Popover, Icon,Select
} from 'antd';
import {connect} from 'dva';
import forEach from 'lodash/forEach';
import JSONData from './JSONData'
import request from '@/utils/request';
import {afterCloseModal, getTimeDistance, flatten} from '@/utils/utils';
import moment from 'moment';
import ReactEcharts from 'echarts-for-react';
import ReactDataGrid from 'react-data-grid';
import find from 'lodash/find';
import MyPagination from "@/components/MyPagination";
import BuildModalTitle from "@/components/BuildModalTitle";
import PressConfig from "@/pages/Pressure_sensors/PressConfig";
import sortBy from 'lodash/sortBy';
import padStart from 'lodash/padStart'

const {Paragraph} = Typography;
const ButtonGroup = Button.Group;
import Loading from '@/components/Loading';
import Config42 from "./Config42";
import Init from "./Init";
const {Option}=Select
const {TabPane} = Tabs;
const {TextArea} = Input;
const { confirm } = Modal;
@connect(({valve_flowmeter_site, loading}) => ({
  valve_flowmeter_site
}))
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      totalVal: 0,
      showType: 1,
      historyData: [],
      historyData2: [],
      historyData_control: [],
      historyData_sensor0: [],
      historyData_sensor1: [],
      historyData_control_line: [],
      showCustom: false,
      activeKey: "1",
      jsonData: '',
      loading: false,
      loading2: false,
      lastData: {},
      pmslastData: {},
      statelastData: {},
      microMotorlastData: {},
      searchParams_control: {
        page: 1,
        per_page: 50,

      },
      searchParams_sensor: {
        page: 1,
        per_page: 50,
      },
      searchParams_control_line: {
        page: 1,
        per_page: 100,
      },
      searchParams: {
        page: 1,
        per_page: 50,
        showType:'',
      },
      searchParams2: {
        page: 1,
        per_page: 50,
      },
      meta: {total: 0, per_page: 50, current_page: 1},
      meta_control: {total: 0, per_page: 50, current_page: 1},
      meta_sensor: {total: 0, per_page: 50, current_page: 1},
      meta_control_line: {total: 0, per_page: 50, current_page: 1},
      meta2: {total: 0, per_page: 50, current_page: 1},
      rangePickerValue: [moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD'), moment(new Date(), 'YYYY-MM-DD')],
      rangePickerValue_control: [moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD'), moment(new Date(), 'YYYY-MM-DD')],
      rangePickerValue_sensor: [moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD'), moment(new Date(), 'YYYY-MM-DD')],
      rangePickerValue_control_line: [moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD'), moment(new Date(), 'YYYY-MM-DD')],
      rangePickerValue2: [moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD'), moment(new Date(), 'YYYY-MM-DD')],
      rangePickerValue_contrast: [ moment(new Date()).add(-1,'days'), moment(new Date(), 'YYYY-MM-DD')],

      changeName: '',
      changeKey: '',
      changeValue: '',
      changeModal: false,
      chan1: '',
      chan2: '',
      detail: {
        row: this.props.editRecord
      },
      contrast:[],
      key:0
    };
  }

  componentDidMount() {
    const that = this;
    const {detail} = this.state;
    if (detail.row.template === 41 || detail.row.template === 40 || detail.row.template === 43) {
      // that.fetch(this.state.searchParams);
      that.fetch_control(this.state.searchParams_control);
      that.fetch_control_line(this.state.searchParams_control_line);
      that.fetch2(this.state.searchParams2);
      that.fetch(this.state.searchParams);
      that.fetchTemplate1Last()
      // that.fetchDataSequentially()
      that.fetchLastTimer = setInterval(function () {
        that.fetch_control_line(that.state.searchParams_control_line);
        that.fetchTemplate1Last()
      }, 10000)
    }
  }

  fetchDataSequentially = async () => {
    let dates = []; // 假设的API端点
    const rangePickerValue_contrast =[moment(this.state.rangePickerValue_contrast[0]).format('YYYY-MM-DD'),moment(this.state.rangePickerValue_contrast[1]).format('YYYY-MM-DD')];
    // 遍历日期区间
    for (let currentDate = moment(rangePickerValue_contrast[0]); currentDate.isSameOrBefore(rangePickerValue_contrast[1]); currentDate.add(1, 'days')) {
      console.log(currentDate.format('YYYY-MM-DD')); // 输出当前日期
      dates.push(currentDate.format('YYYY-MM-DD'))
    }
    if(dates.length>7){
      message.error('日期不能超过7天')
      return false
    }
    this.setState({
      key:this.state.key+1,
      contrast:[]
    },async()=>{
      for (const date of dates) {
        try {
          this.setState({
            loading:true
          })
          const response = await this.fetchHistoryData(date);
          // console.log(`${date} response`,response)
          const json = response.data.data;
          console.log('json',json)
          this.state.contrast.push({date:date,data:json})
          this.setState({
            contrast:this.state.contrast,
          },function (){
            // console.log('this.state.contrast',this.state.contrast)
          })
          if(date===dates[dates.length-1]){
            this.setState({
              Loading:false
            })
          }

        } catch (error) {
          this.setState({
            loading:false
          })
          console.error('Error fetching data:', error);
        }
      }
    })

  };

  fetchHistoryData=(date)=>{
    const that=this
    const {detail} = this.state;
    return request(`/all_workstation_historical_data`, {
      method: 'GET',
      params: {
        start_date: date,
        end_date: date,
        // type: 'rtu03p_multiple',
        type: 'rtu03p_record',
        channel: 0,
        workstation_id: detail.row.id,
        page: 1,
        per_page: 5000
      },
    })
  }

  componentWillUnmount() {
    const that = this;
    if (that.fetchLastTimer) {
      clearInterval(that.fetchLastTimer)
    }

  }

  fetchTemplate1Last = (searchParams) => {
    console.log('获取最新数据')
    const {detail} = this.state;
    const that = this;
    request(`/workstations/${detail.row.id}`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        console.log('获取最新数据', response.data)
        const latest_data = response.data.data.workstation_data
        that.setState({
          detail: {
            row: response.data.data
          }
        })
        if (latest_data.rtu03p_multiple) {
          that.setState({
            lastData: {
              collected_at: latest_data.rtu03p_multiple[0].collected_at,
              parameters: latest_data.rtu03p_multiple[0].parameters.data.valve ? latest_data.rtu03p_multiple[0].parameters.data.valve : {},
            },
            pmslastData: {
              collected_at: latest_data.rtu03p_multiple[0].collected_at,
              parameters: latest_data.rtu03p_multiple[0].parameters.data.pms ? latest_data.rtu03p_multiple[0].parameters.data.pms : {},
            },
            statelastData: {
              collected_at: latest_data.rtu03p_state[0].collected_at,
              parameters: latest_data.rtu03p_state[0].parameters.data.state ? latest_data.rtu03p_state[0].parameters.data.state : {},
            },
            microMotorlastData: {
              collected_at: latest_data.rtu03p_multiple[0].collected_at,
              parameters: latest_data.rtu03p_multiple[0].parameters.data.microMotor ? latest_data.rtu03p_multiple[0].parameters.data.microMotor : {},
            }
          })
        }
        if (latest_data.rtu04p_multiple) {
          that.setState({
            lastData: {
              collected_at: latest_data.rtu04p_multiple[0].collected_at,
              parameters: latest_data.rtu04p_multiple[0].parameters.data.valve ? latest_data.rtu04p_multiple[0].parameters.data.valve : {},
            },
            pmslastData: {
              collected_at: latest_data.rtu04p_multiple[0].collected_at,
              parameters: latest_data.rtu04p_multiple[0].parameters.data.pms ? latest_data.rtu04p_multiple[0].parameters.data.pms : {},
            },
            statelastData: {
              collected_at: latest_data.rtu04p_multiple[0].collected_at,
              parameters: latest_data.rtu04p_state[0].parameters.data.state ? latest_data.rtu04p_state[0].parameters.data.state : {},
            },
            microMotorlastData: {
              collected_at: latest_data.rtu04p_multiple[0].collected_at,
              parameters: latest_data.rtu04p_multiple[0].parameters.data.microMotor ? latest_data.rtu04p_multiple[0].parameters.data.microMotor : {},
            }
          })
        }
        if (latest_data.rtu03p_runtime) {
          that.setState({
            statelastData: {
              collected_at: latest_data.rtu03p_runtime[0].collected_at,
              parameters: latest_data.rtu03p_runtime[0].parameters.data ? latest_data.rtu03p_runtime[0].parameters.data.rtu : {},
            },
          })
        }
        if (latest_data.rtu03p_record) {
          that.setState({
            lastData: {
              collected_at: latest_data.rtu03p_record[0].collected_at,
              parameters: latest_data.rtu03p_record[0].parameters.data.valve ? latest_data.rtu03p_record[0].parameters.data.valve : {},
            },
            pmslastData: {
              collected_at: latest_data.rtu03p_record[0].collected_at,
              parameters: latest_data.rtu03p_record[0].parameters.data.pms ? latest_data.rtu03p_record[0].parameters.data.pms : {},
            },
            microMotorlastData: {
              collected_at: latest_data.rtu03p_record[0].collected_at,
              parameters: latest_data.rtu03p_record[0].parameters.data.microMotor ? latest_data.rtu03p_record[0].parameters.data.microMotor : {},
            },
          })
        }
        if (latest_data.rtu04p_runtime) {
          that.setState({
            statelastData: {
              collected_at: latest_data.rtu04p_runtime[0].collected_at,
              parameters: latest_data.rtu04p_runtime[0].parameters.data ? latest_data.rtu04p_runtime[0].parameters.data : {},
            },
          })
        }
        if (latest_data.rtu04p_record) {
          that.setState({
            lastData: {
              collected_at: latest_data.rtu04p_record[0].collected_at,
              parameters: latest_data.rtu04p_record[0].parameters.data.valve ? latest_data.rtu04p_record[0].parameters.data.valve : {},
            },
            pmslastData: {
              collected_at: latest_data.rtu04p_record[0].collected_at,
              parameters: latest_data.rtu04p_record[0].parameters.data.pms ? latest_data.rtu04p_record[0].parameters.data.pms : {},
            },
            microMotorlastData: {
              collected_at: latest_data.rtu04p_record[0].collected_at,
              parameters: latest_data.rtu04p_record[0].parameters.data.microMotor ? latest_data.rtu04p_record[0].parameters.data.microMotor : {},
            },
          })
        }

      }

    });
  };
  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case 1:
        type = 'check-circle', color = '#0026ff', text = '在线';
        break;
      case -1:
        type = 'close-circle', color = '#fe1b2e', text = '离线';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <AIcon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };
  changeOneParams = (name, key, value) => {
    this.setState({
      changeName: name,
      changeKey: key,
      changeValue: value,
      changeModal: true
    })

  }


  selectDate2 = (type) => {
    const that = this;
    this.setState({
      rangePickerValue2: getTimeDistance(type),
    }, function () {
      that.fetch2({
        ...this.state.searchParams2,
        page: 1,
      });
    });
  };
  handleRangePickerChangeControl = (datePickerValue, type) => {
    const that = this;
    if (type === 'start') {
      this.setState({
        rangePickerValue_control: [datePickerValue, this.state.rangePickerValue2[1]],
      }, function () {
        that.fetch_control({
          ...this.state.searchParams_control,
          page: 1,
        });
      });
    } else {
      this.setState({
        rangePickerValue_control: [this.state.rangePickerValue_control[0], datePickerValue],
      }, function () {
        that.fetch_control({
          ...this.state.searchParams_control,
          page: 1,
        });
      });
    }
  };
  handleRangePickerChangeControlLine = (datePickerValue, type) => {
    const that = this;
    if (type === 'start') {
      this.setState({
        rangePickerValue_control_line: [datePickerValue, this.state.rangePickerValue_control_line[1]],
      }, function () {
        that.fetch_control_line({
          ...this.state.rangePickerValue_control_line,
          page: 1,
        });
      });
    } else {
      this.setState({
        rangePickerValue_control_line: [this.state.rangePickerValue_control_line[0], datePickerValue],
      }, function () {
        that.fetch_control_line({
          ...this.state.rangePickerValue_control_line,
          page: 1,
        });
      });
    }
  };
  handleRangePickerContrast = (datePickerValue, type) => {
    const that = this;
    if (type === 'start') {
      this.setState({
        rangePickerValue_contrast: [datePickerValue, this.state.rangePickerValue_contrast[1]],
      }, function () {
      });
    } else {
      this.setState({
        rangePickerValue_contrast: [this.state.rangePickerValue_contrast[0], datePickerValue],
      }, function () {
      });
    }
  };
  handleRangePickerChange2 = (datePickerValue, type) => {
    const that = this;
    if (type === 'start') {
      this.setState({
        rangePickerValue2: [datePickerValue, this.state.rangePickerValue2[1]],
      }, function () {
        that.fetch2({
          ...this.state.searchParams2,
          page: 1,
        });
      });
    } else {
      this.setState({
        rangePickerValue2: [this.state.rangePickerValue2[0], datePickerValue],
      }, function () {
        that.fetch2({
          ...this.state.searchParams2,
          page: 1,
        });
      });
    }
  };
  fetch2 = (searchParams) => {
    const {detail} = this.state;
    const that = this;
    that.setState({
      loading2: true
    })
    request(`/workstations/${detail.row.id}/protobuf_commands`, {
      method: 'GET',
      params: {
        start_date: that.state.rangePickerValue2[0].format('YYYY-MM-DD'),
        end_date: that.state.rangePickerValue2[1].format('YYYY-MM-DD'),
        ...searchParams,
        order_direction: 'desc'
      },
    }).then((response) => {
      console.log(response);
      if (response.status === 200) {
        this.setState({
          historyData2: response.data.data,
          meta2: response.data.meta,
          searchParams2: searchParams,
          senDataModal: false,
          loading2: false
        });
      }

    });
  };

  isActive(type) {
    const {rangePickerValue} = this.state;
    const value = getTimeDistance(type);
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return false;
    }
    if (rangePickerValue[0].isSame(value[0], 'day') && rangePickerValue[1].isSame(value[1], 'day')) {
      return true;
    }
  }

  isActive2(type) {
    const {rangePickerValue2} = this.state;
    const value = getTimeDistance(type);
    if (!rangePickerValue2[0] || !rangePickerValue2[1]) {
      return false;
    }
    if (rangePickerValue2[0].isSame(value[0], 'day') && rangePickerValue2[1].isSame(value[1], 'day')) {
      return true;
    }
  }

  isActiveLine(type) {
    const {rangePickerValue_control_line} = this.state;
    const value = getTimeDistance(type);
    if (!rangePickerValue_control_line[0] || !rangePickerValue_control_line[1]) {
      return false;
    }
    if (rangePickerValue_control_line[0].isSame(value[0], 'day') && rangePickerValue_control_line[1].isSame(value[1], 'day')) {
      return true;
    }
  }

  selectDate = (type) => {
    const that = this;
    this.setState({
      rangePickerValue: getTimeDistance(type),
    }, function () {
      that.fetch({
        ...this.state.searchParams,
        page: 1,
      });
    });
  };
  selectDateControl = (type) => {
    const that = this;
    this.setState({
      rangePickerValue_control: getTimeDistance(type),
    }, function () {
      that.fetch_control({
        ...this.state.searchParams_control,
        page: 1,
      });
    });
  };
  selectDateControlLine = (type) => {
    const that = this;
    this.setState({
      rangePickerValue_control_line: getTimeDistance(type),
    }, function () {
      that.fetch_control_line({
        ...this.state.rangePickerValue_control_line,
        page: 1,
        per_page: 100,
      });
    });
  };
  fetch = (searchParams) => {
    const {detail} = this.state;
    const that = this;
    that.setState({
      loading: true
    })
    let type = ''
    if (detail.row.template === 41 || detail.row.template === 40 || detail.row.template === 43) {
      if(searchParams.showType==='all'){
        type = ''
      }else{
        type = 'rtu03p_multiple'
      }

    } else if (detail.row.template === 4) {
      type = 'protobuf_modbus'
    }
    request(`/workstation_historical_data`, {
      method: 'GET',
      params: {
        start_date: that.state.rangePickerValue[0].format('YYYY-MM-DD'),
        end_date: that.state.rangePickerValue[1].format('YYYY-MM-DD'),
        ...searchParams,
        type: searchParams.showType,
        channel: 0,
        workstation_id: detail.row.id,
        order_direction: 'desc',
      },
    }).then((response) => {
      console.log(response);
      if (response.status === 200) {
        this.setState({
          historyData: response.data.data,
          meta: response.data.meta,
          searchParams: searchParams,
          loading: false
        });
      }
    });
  };
  fetch_control_line = (searchParams) => {
    const {detail} = this.state;
    const that = this;
    that.setState({
      loading: false
    })

    request(`/workstation_historical_data`, {
      method: 'GET',
      params: {
        start_date: that.state.rangePickerValue_control_line[0].format('YYYY-MM-DD'),
        end_date: that.state.rangePickerValue_control_line[1].format('YYYY-MM-DD'),
        ...searchParams,
        type: 'rtu03p_record',
        channel: 0,
        workstation_id: detail.row.id,
        order_direction: 'desc',
      },
    }).then((response) => {
      console.log(response);
      if (response.status === 200) {
        this.setState({
          historyData_control_line: response.data.data,
          meta_control_line: response.data.meta,
          searchParams_control_line: searchParams,
          loading: false
        });
      }
    });

    that.fetchTemplate1Last()
  };

  fetch_control = (searchParams) => {
    console.log('searchParams', searchParams)
    const {detail} = this.state;
    const that = this;
    that.setState({
      loading: true
    })
    request(`/workstation_historical_data`, {
      method: 'GET',
      params: {
        start_date: that.state.rangePickerValue_control[0].format('YYYY-MM-DD'),
        end_date: that.state.rangePickerValue_control[1].format('YYYY-MM-DD'),
        ...searchParams,
        type: 'rtu03p_record',
        channel: 0,
        workstation_id: detail.row.id,
        order_direction: 'desc',
      },
    }).then((response) => {
      console.log(response);
      if (response.status === 200) {
        this.setState({
          historyData_control: response.data.data,
          meta_control: response.data.meta,
          searchParams_control: searchParams,
          loading: false
        });
      }
    });

  };
  handleRangePickerChange = (datePickerValue, type) => {
    const that = this;
    if (type === 'start') {
      this.setState({
        rangePickerValue: [datePickerValue, this.state.rangePickerValue[1]],
      }, function () {
        that.fetch({
          ...this.state.searchParams,
          page: 1,
        });
      });
    } else {
      this.setState({
        rangePickerValue: [this.state.rangePickerValue[0], datePickerValue],
      }, function () {
        that.fetch({
          ...this.state.searchParams,
          page: 1,
        });
      });
    }
  };
  handleRangePickerChangeSensor = (datePickerValue, type) => {
    const that = this;
    if (type === 'start') {
      this.setState({
        rangePickerValue_sensor: [datePickerValue, this.state.rangePickerValue_sensor[1]],
      }, function () {
        that.fetchSensor({
          ...this.state.searchParams_sensor,
          page: 1,
        });
      });
    } else {
      this.setState({
        rangePickerValue_sensor: [this.state.rangePickerValue_sensor[0], datePickerValue],
      }, function () {
        that.fetchSensor({
          ...this.state.searchParams_sensor,
          page: 1,
        });
      });
    }
  };
  handleConfig = () => {
    const {detail} = this.state;
    const formValues = this.configForm.props.form.getFieldsValue();
    const state = this.configForm.state
    console.log('formValues', formValues);
    const that = this;

    let config = {"cmd": "WRITE_PARAM"};
    if (Number(state.mode) === 0) {
      config.valve_ctrl = {
        "mode": "DISABLE",
        "method": "M0",
        "targets": [
          {
            "time": 0,
            "target": -1,
            "upper_limit": 0
          }
        ]
      }
    }
    if (Number(state.mode) === 1) {
      if (!formValues.method) {
        message.error('控制方法不能为空')
        return false
      }
      config.valve_ctrl = {
        "mode": "IMMEDIATELY",
        "method": Number(formValues.method),
        "targets": [
          {
            "time": 0,
            "target": formValues.method === '0' ? formValues.target_pressure : formValues.target_pressure * 1000,
            "upper_limit": formValues.upper_limit ? formValues.upper_limit * 1000 : 0
          }
        ]
      }
    }
    if (Number(state.mode) === 2) {
      let itemsKey = []
      for (let i in formValues) {
        let splitKey = i.split('-')
        let len = splitKey.length;
        if (len >= 2) {
          if (itemsKey.indexOf(splitKey[1]) < 0) {
            itemsKey.push(splitKey[1])
          }
        }
      }
      if (itemsKey.length > 24) {
        message.error('时间个数不能超过24')
        return
      }
      const metersArr = []
      for (let i = 0; i < itemsKey.length; i++) {
        if (formValues[`time-${itemsKey[i]}`]) {
          const target = formValues.method === '0' ? formValues[`pressure-${itemsKey[i]}`] : parseInt(formValues[`pressure-${itemsKey[i]}`] * 1000) ;
          const upper_limit = formValues.method === '0' ? formValues[`upper_limit-${itemsKey[i]}`]:parseInt(formValues[`upper_limit-${itemsKey[i]}`] * 1000);
          let time = moment(formValues[`time-${itemsKey[i]}`]).subtract(8, 'h')
          console.log('time', time.format('HH:mm:ss'))
          metersArr.push({
            time: parseInt(moment(time).hours()) * 60 * 60 + parseInt(moment(time).minutes()) * 60 + parseInt(moment(time).seconds()),
            "target": target,
            "upper_limit": upper_limit
          })
        }

      }
      const sortMetersArr = sortBy(metersArr, function (o) {
        return o.time;
      })
      config.valve_ctrl = {
        "mode": "FIXED_TIME",
        "method":  Number(formValues.method),
        "targets": sortMetersArr
      }
    }
    console.log(config)
    request(`/workstations/${detail.row.id}/protobuf_commands`, {
      method: 'POST',
      data: {
        command: {rtu03: config}
      }
    }).then((response) => {
      console.log(response);
      if (response.status === 200) {
        message.success('下发指令成功')
        that.setState({
          diandaofaModal: false,
          shuilifadianModal: false,
        });
        that.fetch2(this.state.searchParams2);

      }
    })
  };
  initCommand = () => {
    const formValues = this.initForm.props.form.getFieldsValue();
    const that = this;
    const {
      dispatch
    } = this.props;
    const {detail} = this.state;
    let commands = {}
    if (detail.row.template === 40 || detail.row.template === 41 || detail.row.template === 43) {
      if (detail.row.template === 41) {


        commands = {
          "rtu03": {
            "cmd": "WRITE_PARAM",
            "device_cfg": {
              "state_interval": formValues.state_interval,
              "record_interval": formValues.record_interval
            },
            "sensor_cfg": {
              "type": formValues.type,
              "range": formValues.range*1000,
              "wave":  formValues.wave*1000
            },
            "valve_cfg": {
              "enable": true,
              "method_m1_param": {
                "p0": formValues.p0,
                "p1": formValues.p1,
                "p2": formValues.p2,
                "p3": formValues.p3
              }
            },
            "pms_cfg": {
              "enable": false
            },
            "micro_motor_cfg": {
              "enable": false
            }
          }
        }
      }
      if (detail.row.template === 40) {
        commands = {
          "rtu03": {
            "cmd": "WRITE_PARAM",
            "device_cfg": {
              "state_interval": formValues.state_interval,
              "record_interval": formValues.record_interval
            },
            "sensor_cfg": {
              "type": formValues.type,
              "range": formValues.range*1000,
              "wave":  formValues.wave*1000
            },
            "valve_cfg": {
              "enable": true,
              "method_m1_param": {
                "p0": formValues.p0,
                "p1": formValues.p1,
                "p2": formValues.p2,
                "p3": formValues.p3
              }
            },
            "pms_cfg": {
              "enable": false
            },
            "micro_motor_cfg": {
              "enable": true,
              "delay": formValues.delay
            }
          }
        }
      }
      if (detail.row.template === 43) {
        commands = {
          "rtu03": {
            "cmd": "WRITE_PARAM",
            "device_cfg": {
              "state_interval": formValues.state_interval,
              "record_interval": formValues.record_interval
            },
            "sensor_cfg": {
              "type": formValues.type,
              "range": formValues.range*1000,
              "wave":  formValues.wave*1000
            },
            "valve_cfg": {
              "enable": true,
              "method_m1_param": {
                "p0": formValues.p0,
                "p1": formValues.p1,
                "p2": formValues.p2,
                "p3": formValues.p3
              }
            },
            "pms_cfg": {
              "enable": true
            },
            "micro_motor_cfg": {
              "enable": true,
              "delay": formValues.delay
            }
          }
        }
      }


    }
    const sendData={
      ...detail.row,
      hardware_configs: {
        ...detail.row.hardware_configs,
        protobuf_json: {
          ...commands
        }
      }
    }
    let formData = new FormData();
    formData.append("id",  detail.row.id);
    formData.append("type", sendData.type);
    formData.append("address", sendData.address);
    formData.append("hardware_model", sendData.hardware_model);
    formData.append("area", sendData.area);
    formData.append("imei", sendData.imei);
    formData.append("sort", sendData.sort);
    formData.append("name", sendData.name);
    formData.append("longitude", sendData.longitude);
    formData.append("latitude", sendData.latitude);
    formData.append("template",sendData.template);
    formData.append("hardware_configs",  JSON.stringify(sendData.hardware_configs));
    this.props.dispatch({
      type: `valve_flowmeter_site/edit`,
      payload: {
        formData:formData,
        id: detail.row.id
      },
      callback() {
        message.success('初始化指令下发成功')
        that.setState({
          initModal: false
        })
        const {
          valve_flowmeter_site: {searchParams},
        } = that.props;
        dispatch({
          type: 'valve_flowmeter_site/fetch',
          payload: {
            ...searchParams,
          },
          callback() {
            that.fetchTemplate1Last()
          },
        });
      },
    })
  };
  reboot = () => {
    const that = this;
    const {dispatch} = this.props;
    const {detail} = this.state;
    request(`/workstations/${detail.row.id}/protobuf_commands`, {
      method: 'POST',
      data: {
        command: {
          "rtu03": {
            "cmd": 0
          }
        }
      }
    }).then((response) => {
      console.log(response);
      if (response.status === 200) {
        message.success('重启命令下发成功')
        that.fetch2(this.state.searchParams2);

      }
    })
  }
  getOption = () => {
    const {detail} = this.state;
    const template = detail.row.template;
    const that=this;

    const historyData_control_line = JSON.parse(JSON.stringify(this.state.historyData_control_line)).reverse();

    // console.log('historyData_control_line',historyData_control_line)
    let lastMonth = [];
    let legend = [];
    let series = []
    let time = [];
    let faqian = [];
    let fahou = [];
    let ops = [];
    let pos = [];
    let state = [];
    let method = [];
    let targetPos = [];
    let actualPos = [];
    let target = [];
    let upperLimit = [];
    let mode = [];
    for (let j = 0; j < historyData_control_line.length; j++) {
      time.push(historyData_control_line[j].collected_at);
      let parameters = historyData_control_line[j].data.data.record;
      // console.log('parameters',parameters)
      let chan0 = 0
      let chan1 = 0
      if (parameters.sensors) {
        for (let i = 0; i < parameters.sensors.length; i++) {
          if (parameters.sensors[i]) {
            if (parameters.sensors[i].chan === 1) {
              if (parameters.sensors[i].value) {
                chan1 = parameters.sensors[i].value / 1000
              } else {
                chan1 = 0
              }
            }
            if (!parameters.sensors[i].chan && parameters.sensors[i].value) {
              chan0 = parameters.sensors[i].value / 1000
            }
          }
        }


      } else {
      }
      if(parameters.valve){
        mode.push(parameters.valve.mode?parameters.valve.mode:'DISABLE')
      }else{
        mode.push('DISABLE')
      }

      if(parameters.valve&&parameters.valve.method){
        method.push(parameters.valve.method)
      }else{
        method.push('M0')
      }
      if(parameters.valve&&parameters.valve.targetPos){
        targetPos.push(parameters.valve.targetPos)
      }else{
        targetPos.push('0')
      }
      if(parameters.valve&&parameters.valve.actualPos){
        actualPos.push(parameters.valve.actualPos)
      }else{
        actualPos.push('0')
      }
      if(parameters.valve&&parameters.valve.target){
        target.push(parameters.valve.method==='M1'?parameters.valve.target.target/1000:parameters.valve.target.target?parameters.valve.target.target:'0')
      }else{
        target.push('0')
      }
      if(parameters.valve&&parameters.valve.target){
        upperLimit.push(parameters.valve.target.upperLimit?parameters.valve.target.upperLimit/1000:0)
      }else{
        upperLimit.push('0')
      }
      if(parameters.microMotor&&parameters.microMotor.ops ==='CLOSE'){
        ops.push('关阀')
      }else if(parameters.microMotor&&parameters.microMotor.ops ==='OPEN'){
        ops.push('开阀')
      }else if(parameters.microMotor&&parameters.microMotor.ops ==='BRAKE'){
        ops.push('停止')
      }else if(parameters.microMotor&&parameters.microMotor.ops ==='NOTHING'){
        ops.push('无操作')
      }else{
        ops.push('关阀')
      }
      if(parameters.microMotor&&parameters.microMotor.pos ==='ABNORMAL'){
        pos.push('异常')
      }else if(parameters.microMotor&&parameters.microMotor.pos ==='CLOSED'){
        pos.push('关闭')
      }else if(parameters.microMotor&&parameters.microMotor.pos ==='OPENED'){
        pos.push('打开')
      }else if(parameters.microMotor&&parameters.microMotor.pos ==='UNKNOWN'){
        pos.push('未知')
      }else{
        pos.push('异常')
      }
      if(parameters.microMotor&&parameters.microMotor.state ==='MOVE'){
        state.push('移动')
      }else if(parameters.microMotor&&parameters.microMotor.state ==='STOP'){
        state.push('停止')
      }else if(parameters.microMotor&&parameters.microMotor.state ==='JAM'){
        state.push('阻塞')
      }else if(parameters.microMotor&&parameters.microMotor.state ==='FAULT'){
        state.push('故障')
      }else{
        state.push('移动')
      }
      faqian.push(chan0)
      fahou.push(chan1)
    }
    let parseData = [];
    parseData = faqian.map((item, index) => {
      return [(moment(time[index], "YYYY-MM-DD  HH:mm:ss").diff(moment(time[0], "YYYY-MM-DD  HH:mm:ss"))) / 1000, item]
    });
    let parseData2 = [];
    parseData2 = fahou.map((item, index) => {
      return [(moment(time[index], "YYYY-MM-DD  HH:mm:ss").diff(moment(time[0], "YYYY-MM-DD  HH:mm:ss"))) / 1000, item]
    });

    // console.log('parseData',parseData)
    // console.log('parseData2',parseData2)
    let option = {
      background: 'rgb(0,0,0)',
      title: {
        text: ''
      },
      toolbox: {
        show: true,
        feature: {
          dataView: {readOnly: true},
        },
        emphasis: {
          iconStyle: {
            color: "rgb(255,255,255)"
          }
        },
      },
      animation: false,
      color: ['#da0422', '#00da4a', '#008cff', '#f0b100'],
      tooltip: {
        trigger: 'axis',
        formatter:function (params){
          // console.log('params',params)
          // let text=params[0].axisValue+'<br/>'
          let text=(moment(time[0]).add(params[0].data[0], 's')).format('MM-DD HH:mm:ss')+'<br/>'

          for(let i=0;i<params.length;i++){
            text+="<span style=font-weight:bold;color:"+params[i].color+">"+params[i].seriesName+ ":"+params[i].data[1]+" Mpa</span><br/>"
          }
          if(mode[params[0].dataIndex]!=='DISABLE'){
            text+=`控制方法 : ${method[params[0].dataIndex]}<br/>`
            text+=`目标位置 : ${targetPos[params[0].dataIndex]}<br/>`
            text+=`实际位置 : ${actualPos[params[0].dataIndex]}<br/>`
            text+=`控制参数<br/>`
            text+=`<span style='margin-left: 20px'></span>*目标 : ${target[params[0].dataIndex]}<br/>`
            text+=`<span style="margin-left: 20px"></span>*上限 : ${upperLimit[params[0].dataIndex]}<br/>`
          }

          if(template===40||template===43){
            text+=`泄压球阀<br/>`
            text+=`<span style="margin-left: 20px"></span>*目标 : ${ops[params[0].dataIndex]}<br/>`
            text+=`<span style="margin-left: 20px"></span>*位置 : ${pos[params[0].dataIndex]}<br/>`
          }

          return text
        }
      },
      legend: {
        data: ['阀前压力', '阀后压力']
      },
      grid: {
        left: '2%',
        right: '3%',
        top: '8%',
        bottom: '2%',
        containLabel: true
      },
      dataZoom: [
        {
          type: 'slider',
          show: false,
          xAxisIndex: [0],
        },
        {
          type: 'inside',
          xAxisIndex: [0],
        },
      ],
      xAxis: {
        type: 'value',
        boundaryGap: false,
        // data:time,
        axisLabel: {
          showMaxLabel: true,
          formatter: function (value, index) {
            return (moment(time[0]).add(value, 's')).format('MM-DD HH:mm:ss')
          }
        }
      },
      // xAxis: {
      //   type: 'category',
      //   boundaryGap: false,
      //   data: time,
      //
      // },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} Mpa',
        },
      },
      series: [{
        name: '阀前压力',
        type: 'line',
        smooth: true,
        lineStyle: {
          normal: {
            width: 4,
          }
        },
        itemStyle: {
          normal: {
            label: {
              show: true,
              position: 'top',
              textStyle: {
                fontSize: 16,
                color: "#fff"
              },
              formatter: (params) => {
                // console.log('params',params)
                if (faqian.length - 1 == params.dataIndex) {
                  return params.value[1]
                } else {
                  return ""
                }
              },
            },
          }
        },
        // data: faqian
        data: parseData
      }, {
        name: '阀后压力',
        type: 'line',
        smooth: true,
        lineStyle: {
          normal: {
            width: 4,
          }
        },
        itemStyle: {
          normal: {
            label: {
              show: true,
              position: 'top',
              textStyle: {
                fontSize: 16,
                color: "#fff"
              },
              formatter: (params) => {
                if (fahou.length - 1 == params.dataIndex) {
                  return params.value[1]
                } else {
                  return ""
                }
              },
            },
          }
        },
        data: parseData2,
        // data: fahou
      }]
    };
    return option;
  };
  getContrastOption= (type) => {
    const {detail,contrast} = this.state;
    const template = detail.row.template;
    const that=this;
    const historyData_control_line = JSON.parse(JSON.stringify(this.state.historyData_control_line)).reverse();

    // console.log('historyData_control_line',historyData_control_line)
    let lastMonth = [];
    let legend = [];
    let  series=[];
    for(let i=0;i<contrast.length;i++){
      legend.push(contrast[i].date)
      let seriesItem=contrast[i].data;
      let time = [];
      let faqian = [];
      let fahou = [];
      for (let j = 0; j < seriesItem.length; j++) {
        time.push(moment(seriesItem[j].collected_at).format('HH:mm:ss'));
        let parameters = seriesItem[j].data.data.record;
        // console.log('parameters',parameters)
        let chan0 = 0
        let chan1 = 0
        if (parameters.sensors) {
          for (let i = 0; i < parameters.sensors.length; i++) {
            if (parameters.sensors[i]) {
              if (parameters.sensors[i].chan === 1) {
                if (parameters.sensors[i].value) {
                  chan1 = parameters.sensors[i].value / 1000
                } else {
                  chan1 = 0
                }
              }
              if (!parameters.sensors[i].chan && parameters.sensors[i].value) {
                chan0 = parameters.sensors[i].value / 1000
              }
            }
          }


        } else {
        }

        faqian.push(chan0)
        fahou.push(chan1)

      }
      // console.log('time',time)
      let parseData = [];
      parseData = faqian.map((item, index) => {
        return [(moment(time[index], "HH:mm:ss").diff(moment("00:00:00", "HH:mm:ss"))) / 1000, item]
      });
      let parseData2 = [];
      parseData2 = fahou.map((item, index) => {
        return [(moment(time[index], "HH:mm:ss").diff(moment("00:00:00", "HH:mm:ss"))) / 1000, item]
      });
      // console.log('parseData',parseData)
      // console.log('parseData2',parseData2)
      series.push({
        name: contrast[i].date,
        type: 'line',
        smooth: true,
        large: true,
        lineStyle: {
          normal: {
            width: 2,
          }
        },
        itemStyle: {
          normal: {
            label: {
              show: true,
              position: 'top',
              textStyle: {
                fontSize: 16,
                color: "#fff"
              },
              formatter: (params) => {
                // console.log('params',params)
                if (faqian.length - 1 == params.dataIndex) {
                  return params.value[1]
                } else {
                  return ""
                }
              },
            },
          }
        },
        // data: faqian
        data: type==='faqian'?parseData:parseData2
      })
    }
    // console.log('legend',legend)
    // console.log('parseData',parseData)
    // console.log('parseData2',parseData2)
    let option = {
      background: 'rgb(0,0,0)',
      title: {
        text: type==='faqian'?'阀前压力':'阀后压力'
      },
      toolbox: {
        show: true,
        feature: {
          dataView: {readOnly: true},
        },
        emphasis: {
          iconStyle: {
            color: "rgb(255,255,255)"
          }
        },
      },
      animation: false,
      // color: ['#da0422', '#00da4a', '#008cff', '#f0b100'],
      tooltip: {
        trigger: 'axis',
        formatter:function (params){
          // console.log('params',params)
          // let text=params[0].axisValue+'<br/>'
          let text=(moment("00:00:00", "HH:mm:ss").add(params[0].data[0], 's')).format('HH:mm:ss')+'<br/>'

          for(let i=0;i<params.length;i++){
            text+="<span style=font-weight:bold;color:"+params[i].color+">"+params[i].seriesName+ ":"+params[i].data[1]+" Mpa</span><br/>"
          }
          return text
        }
      },
      legend: {
        data: legend
      },
      grid: {
        left: '2%',
        right: '3%',
        top: '15%',
        bottom: '2%',
        containLabel: true
      },
      dataZoom: [
        {
          type: 'slider',
          show: false,
          xAxisIndex: [0],
        },
        {
          type: 'inside',
          xAxisIndex: [0],
        },
      ],
      xAxis: {
        type: 'value',
        boundaryGap: false,
        // data:time,
        axisLabel: {
          showMaxLabel: true,
          formatter: function (value, index) {
            return (moment("00:00:00", "HH:mm:ss").add(value, 's')).format('HH:mm:ss')
          }
        }
      },
      // xAxis: {
      //   type: 'category',
      //   boundaryGap: false,
      //   data: time,
      //
      // },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} Mpa',
        },
      },
      series:series
    };
    return option;
  };
  hexToBinary = (hex) => {
    if (!hex) {
      return parseInt(0, 16).toString(2);
    } else {
      return parseInt(hex, 16).toString(2);
    }

  }

  render() {
    const defaultColumnProperties = {
      resizable: true,
    };
    const {detail} = this.state;
    console.log('detail',detail)
    const {loading2, loading} = this.state
    const columns = [
      {
        name: '上传时间',
        width: 160,
        key: 'collected_at',
      },
      {
        name: 'DATA',
        width: 711,
        key: 'data',
        formatter: (event) => {
          return <div style={{position: 'relative'}}>
            <TextArea
              value={JSON.stringify(event.row.data)}
              autoSize={{minRows: 1, maxRows: 1}}
            />

          </div>;
        },
      },
      {
        name: '操作',
        width: 160,
        key: 'operate',
        formatter: (event) => {
          return <Button onClick={() => {
            this.setState({
              retry: false,
              infoModal: true,
              jsonData: event.row.data
            })
          }} type={'primary'} size={'small'} className={'btn-cyan'}>详情</Button>;
        },
      },
    ].map(c => ({...defaultColumnProperties, ...c}));
    const columnsSensor = [
      {
        name: '上传时间',
        width: 160,
        key: 'collected_at',
      },
      {
        name: 'DATA(阀前)',
        width: 400,
        key: 'data0',
        formatter: (event) => {
          return <div style={{position: 'relative'}}>
            <TextArea
              value={JSON.stringify(event.row.data0)}
              autoSize={{minRows: 1, maxRows: 1}}
            />

          </div>;
        },
      },
      {
        name: 'DATA(阀后)',
        width: 400,
        key: 'data1',
        formatter: (event) => {
          return <div style={{position: 'relative'}}>
            <TextArea
              value={JSON.stringify(event.row.data1)}
              autoSize={{minRows: 1, maxRows: 1}}
            />

          </div>;
        },
      },
    ].map(c => ({...defaultColumnProperties, ...c}));

    const columns2 = [
      {
        name: '下发时间',
        width: 160,
        key: 'created_at',
      },
      {
        name: '指令',
        width: 711,
        key: 'original_content',
        formatter: (event) => {
          return <div style={{position: 'relative'}}>
            <TextArea
              value={JSON.stringify(event.row.original_content)}
              autoSize={{minRows: 1, maxRows: 1}}
            />
            <br/>

          </div>;
        },
      },
      {
        name: '操作',
        width: 160,
        key: 'operate',
        formatter: (event) => {
          return <Button onClick={() => {
            this.setState({
              retry: true,
              infoModal: true,
              jsonData: event.row.original_content,

            })
          }} type={'primary'} size={'small'} className={'btn-cyan'}>详情</Button>
        },
      },
    ].map(c => ({...defaultColumnProperties, ...c}));
    const reverceData = [...this.state.historyData];
    const meta = this.state.meta
    const meta2 = this.state.meta2
    const meta_control = this.state.meta_control
    const historyData_control = [...this.state.historyData_control];
    const historyData_sensor0 = [...this.state.historyData_sensor0];
    const historyData_sensor1 = [...this.state.historyData_sensor1];
    let sensorData = []
    if (historyData_sensor0.length === historyData_sensor1.length) {
      for (let i = 0; i < historyData_sensor0.length; i++) {
        sensorData.push({
          collected_at: historyData_sensor0[i].collected_at,
          data0: historyData_sensor0[i].data,
          data1: historyData_sensor1[i].data,
        })
      }
    }

    const reverceData2 = [...this.state.historyData2];
    const temObj = [{id: 1, name: '电流型压力传感器 + 电导阀', type: 'ECD-03'},
      {id: 40, name: '电流型压力传感器 + 电导阀 + 泄压微电机', type: 'ECD-03'},
      {id: 3, name: '电流型压力传感器 + 电导阀 + 泄压微电机 + 电源管理', type: 'ECD-03'},
      {id: 4, name: '普华智能水力发电机(新)', type: ''}]
    let interval = '';
    let recordInterval = '';
    let delay='';
    const wave = detail.row.hardware_configs.protobuf_json ?
      detail.row.hardware_configs.protobuf_json.rtu03.sensor_cfg.wave / 1000 : '';
    const range = detail.row.hardware_configs.protobuf_json ?
      detail.row.hardware_configs.protobuf_json.rtu03.sensor_cfg.range / 1000 : '';
    const type = detail.row.hardware_configs.protobuf_json ?
      detail.row.hardware_configs.protobuf_json.rtu03.sensor_cfg.type : '';
    let p0 = detail.row.hardware_configs.protobuf_json ?
      detail.row.hardware_configs.protobuf_json.rtu03.valve_cfg.method_m1_param.p0 : '';
    let p1 = detail.row.hardware_configs.protobuf_json ?
      detail.row.hardware_configs.protobuf_json.rtu03.valve_cfg.method_m1_param.p1 : '';
    let p2 = detail.row.hardware_configs.protobuf_json ?
      detail.row.hardware_configs.protobuf_json.rtu03.valve_cfg.method_m1_param.p2 : '';
    let p3 = detail.row.hardware_configs.protobuf_json ?
      detail.row.hardware_configs.protobuf_json.rtu03.valve_cfg.method_m1_param.p3 : '';
    interval = detail.row.hardware_configs.protobuf_json ?
      detail.row.hardware_configs.protobuf_json.rtu03.device_cfg.state_interval : '';
    recordInterval = detail.row.hardware_configs.protobuf_json ?
      detail.row.hardware_configs.protobuf_json.rtu03.device_cfg.record_interval : '';
    delay = detail.row.hardware_configs.protobuf_json ?
      detail.row.hardware_configs.protobuf_json.rtu03.micro_motor_cfg.delay : '';
    if (detail.row.template === 4) {
      interval = detail.row.hardware_configs.protobuf_json ?
        detail.row.hardware_configs.protobuf_json.rtu02.control.modbusReads[0].notify.cycle.interval : '';
    }
    const that = this;
    const lastData = this.state.lastData
    const pmslastData = this.state.pmslastData
    const statelastData = this.state.statelastData
    const microMotorlastData = this.state.microMotorlastData
    console.log('microMotorlastData', microMotorlastData.parameters)
    return (
      <div className="custom-card">
        <div className="table-page">
          <div>
            <Tabs onTabClick={(e) => {
              console.log(e)
              if (e === 4) {
              }
            }} activeKey={this.state.activeKey} defaultActiveKey={"1"} onChange={(e) => {
              this.setState({
                activeKey: e
              })
            }} >
              <TabPane tab="设备信息" key={"1"}>
                <Descriptions column={4} title={<div><AIcon style={{
                  fontSize: '18px', position: 'relative', color: 'blue', marginRight: '5px',
                  top: '2px'
                }} type="appstore"/>基本信息</div>} bordered>
                  <Descriptions.Item label="站点名称" span={1}> <Tooltip
                    title={detail.row.name}>{detail.row.name}</Tooltip>

                  </Descriptions.Item>
                  {/* <Descriptions.Item label="设备型号" span={1}> {find(temObj, function (o) {
                    return o.id === detail.row.template
                  }).type}</Descriptions.Item> */}
                  <Descriptions.Item label="在线状态"
                                     span={1}>{this.renderStatus(detail.row.online_status)}</Descriptions.Item>
                  {/*<Descriptions.Item label="登录时间" span={1}>{detail.row.logined_at}</Descriptions.Item>*/}
                  <Descriptions.Item label="创建时间" span={1}>{detail.row.created_at}</Descriptions.Item>
                  <Descriptions.Item label="安装地址" span={1}><Tooltip
                    title={detail.row.address}>{detail.row.address}</Tooltip>

                  </Descriptions.Item>
                  <Descriptions.Item label="站点描述" span={1}>
                    <Tooltip
                      title={detail.row.description}>{detail.row.description}</Tooltip>


                  </Descriptions.Item>
                </Descriptions>


                <Descriptions column={4} title={<div><AIcon style={{
                  fontSize: '18px', position: 'relative', color: 'blue', marginRight: '5px',
                  top: '2px'
                }} type="bank"/>硬件信息</div>} bordered style={{marginTop: '22px'}}>
                  <Descriptions.Item label="IMEI" span={1}> <Tooltip
                    title={detail.row.imei}>{detail.row.imei}</Tooltip></Descriptions.Item>
                  <Descriptions.Item label="ICCID" span={1}> <Tooltip
                    title={detail.row.hardware_information.rtu ?
                      detail.row.hardware_information.rtu.iccid : ''}>{detail.row.hardware_information.rtu ?
                    detail.row.hardware_information.rtu.iccid : ''}</Tooltip></Descriptions.Item>
                  <Descriptions.Item label="固件版本号" span={1}> <Tooltip
                    title={detail.row.hardware_information.rtu ?
                      detail.row.hardware_information.rtu.ver : ''}>{detail.row.hardware_information.rtu ?
                    detail.row.hardware_information.rtu.ver : ''}</Tooltip></Descriptions.Item>
                  <Descriptions.Item label="PSM周期" span={1}> <Tooltip
                    title={detail.row.hardware_information.nb ?
                      detail.row.hardware_information.nb.psmPeriodic : ''}>{detail.row.hardware_information.nb ?
                    detail.row.hardware_information.nb.psmPeriodic : ''}</Tooltip></Descriptions.Item>
                  <Descriptions.Item label="PSM活动时间" span={1}> <Tooltip
                    title={detail.row.hardware_information.nb ?
                      detail.row.hardware_information.nb.psmActive : ''}>{detail.row.hardware_information.nb ?
                    detail.row.hardware_information.nb.psmActive : ''}</Tooltip></Descriptions.Item>
                  <Descriptions.Item label="登录生命周期" span={1}> <Tooltip
                    title={detail.row.hardware_information.session ?
                      detail.row.hardware_information.session.lifetime : ''}>{detail.row.hardware_information.session ?
                    detail.row.hardware_information.session.lifetime : ''}</Tooltip></Descriptions.Item>
                  <Descriptions.Item label="运行时间" span={1}> <Tooltip
                    title={statelastData.parameters ?
                      statelastData.parameters.uptime : ''}>{statelastData.parameters ?
                    statelastData.parameters.uptime : ''}</Tooltip></Descriptions.Item>
                  <Descriptions.Item label="供电电压" span={1}> <Tooltip
                    title={statelastData.parameters ?
                      statelastData.parameters.power : ''}>{statelastData.parameters ?
                    statelastData.parameters.power : ''}</Tooltip></Descriptions.Item>
                  <Descriptions.Item label="网络质量(RSSI)" span={1}> <Tooltip
                    title={statelastData.parameters ?
                      statelastData.parameters.rssi : ''}>{statelastData.parameters ?
                    statelastData.parameters.rssi : ''}</Tooltip></Descriptions.Item>
                  <Descriptions.Item label="网络信噪比(SNR)" span={1}> <Tooltip
                    title={statelastData.parameters ?
                      statelastData.parameters.snr : ''}>{statelastData.parameters ?
                    statelastData.parameters.snr : ''}</Tooltip></Descriptions.Item>
                </Descriptions>

                <Descriptions column={3} title={<div><AIcon style={{
                  fontSize: '18px', position: 'relative', color: 'blue', marginRight: '5px',
                  top: '2px'
                }} type="tags"/>模板参数 <Button onClick={() => {
                  this.setState({initModal: 'true'})
                }} type={'primary'} size={'small'}>初始化</Button>
                  <Button style={{marginLeft:'10px'}} onClick={() => {
                    confirm({
                      title: `确定要重启当前设备吗?`,
                      content: '请谨慎操作！',
                      okText: '确定',
                      okType: 'danger',
                      cancelText: '取消',
                      centered: true,
                      maskClosable: true,
                      onOk() {
                        that.reboot();
                      },
                      onCancel() {
                        console.log('Cancel');
                      },
                    });
                  }} type={'primary'} size={'small'}>重启</Button>
                </div>} bordered style={{marginTop: '22px'}}>
                  <Descriptions.Item label="模板名称" span={1}>
                    <Tooltip
                      title={find(temObj, function (o) {
                        return o.id === detail.row.template
                      }).name}>
                      {find(temObj, function (o) {
                        return o.id === detail.row.template
                      }).name}
                    </Tooltip>
                  </Descriptions.Item>
                  <Descriptions.Item label="传感器类型" span={1}>
                    {(type==='CURRENT'||type===0)?'电流类型':'电压类型'}

                  </Descriptions.Item>
                  <Descriptions.Item label="压力传感器量程(MPa)" span={1}>
                    {range}

                  </Descriptions.Item>
                  <Descriptions.Item label="波动值(MPa)" span={1}>
                    {wave}

                  </Descriptions.Item>
                  <Descriptions.Item label="设备状态上传间隔(秒)" span={1}>
                    {interval}

                  </Descriptions.Item>
                  <Descriptions.Item label="数据采集上传间隔(秒)" span={1}>
                    {recordInterval}

                  </Descriptions.Item>
                  <Descriptions.Item label="泄压微电机控制延时(秒)" span={1}>
                    {delay}

                  </Descriptions.Item>
                  <Descriptions.Item label="P0" span={1}>
                    {p0}

                  </Descriptions.Item>
                  <Descriptions.Item label="P1" span={1}>
                    {p1}

                  </Descriptions.Item>
                  <Descriptions.Item label="P2" span={1}>
                    {p2}

                  </Descriptions.Item>
                  <Descriptions.Item label="P3" span={1}>
                    {p3}

                  </Descriptions.Item>

                </Descriptions>

              </TabPane>
              {
                (detail.row.template === 41 || detail.row.template === 40 || detail.row.template === 43) &&
                <TabPane forceRender={true} tab="详情" key={"6"}
                         style={{overflowY: 'scroll', height: 'calc(100vh - 230px)'}}>
                  <div style={{position: 'relative', overflow: 'hidden'}}>

                    {
                      loading && <Loading/>
                    }
                    <div style={{marginBottom: '10px'}}>
                      <ButtonGroup>
                        <Button onClick={() => this.selectDateControlLine('month')}
                                type={this.isActiveLine('month') ? 'primary' : ''}>本月</Button>
                        <Button onClick={() => this.selectDateControlLine('year')}
                                type={this.isActiveLine('year') ? 'primary' : ''}>本年</Button>
                      </ButtonGroup>

                      <DatePicker
                        value={this.state.rangePickerValue_control_line[0]}
                        allowClear={false}
                        format="YYYY-MM-DD"
                        style={{width: 150}}
                        placeholder={'开始日期'}
                        onChange={(e) => this.handleRangePickerChangeControlLine(e, 'start')}
                      />
                      <DatePicker
                        allowClear={false}
                        value={this.state.rangePickerValue_control_line[1]}
                        format="YYYY-MM-DD"
                        placeholder={'结束日期'}
                        style={{width: 150}}
                        onChange={(e) => this.handleRangePickerChangeControlLine(e, 'end')}
                      />
                      <Button onClick={() => this.fetch_control_line({
                        ...this.state.searchParams_control_line,
                        page: 1,
                      })} type={'primary'}>刷新</Button>

                    </div>
                    <div><ReactEcharts
                      option={this.getOption()}
                      style={{height: 350, width: '100%'}}
                      theme='my_theme'
                      //onChartReady={this.onChartReadyCallback}
                      //onEvents={EventsDict}
                    />
                    </div>
                    <div style={{marginTop: '10px', float: 'right'}}>
                      <MyPagination searchCondition={{...this.state.searchParams_control_line}}
                                    meta={this.state.meta_control_line} handleSearch={this.fetch_control_line}/>

                    </div>
                  </div>
                  <Tabs>

                    <TabPane forceRender={true} tab={
                      <span>
         智能电导阀       <Icon type="setting" onClick={() => {
                        this.setState({diandaofaModal: true})
                      }}/>
        </span>
                    } key={"62"}>
                      <Descriptions column={4} title={''} bordered>
                        {[{title: "供电电压", key: 'volt'},
                          {title: "供电电流", key: 'current'},
                          {title: "目标位置", key: 'targetPos'},
                          {title: "实际位置", key: 'actualPos'},
                          {title: "电机动作", key: 'ops'},
                          {title: "错误标记", key: 'errorFalgs'},
                          {title: "零位检测", key: 'zeroPos'},
                        ].map((item, index) => {
                          return <Descriptions.Item key={item.key} label={item.title} span={1}>  {lastData.parameters ?
                            lastData.parameters[item.key] ? lastData.parameters[item.key].toString() : '0' : '0'}</Descriptions.Item>
                        })}
                      </Descriptions>
                    </TabPane>
                    {
                      detail.row.template !== 41 &&
                      <TabPane forceRender={true} tab={
                        <span>
                      微电机
                    </span>
                      } key={"63"}>
                        <Descriptions column={4} title={''} bordered>
                          {[{title: "目标", key: 'ops'},
                            {title: "位置", key: 'pos'},
                            {title: "状态", key: 'state'},
                          ].map((item, index) => {
                            if (microMotorlastData.parameters && microMotorlastData.parameters[item.key] && item.key === 'ops') {
                              if (microMotorlastData.parameters[item.key] === 'BRAKE') {
                                return <Descriptions.Item key={item.key} label={item.title}
                                                          span={1}> 停止</Descriptions.Item>
                              }
                              if (microMotorlastData.parameters[item.key] === 'CLOSE') {
                                return <Descriptions.Item key={item.key} label={item.title}
                                                          span={1}> 关阀</Descriptions.Item>
                              }
                              if (microMotorlastData.parameters[item.key] === 'OPEN') {
                                return <Descriptions.Item key={item.key} label={item.title}
                                                          span={1}> 开阀</Descriptions.Item>
                              }
                              if (microMotorlastData.parameters[item.key] === 'NOTHING') {
                                return <Descriptions.Item key={item.key} label={item.title}
                                                          span={1}> 无操作</Descriptions.Item>
                              }
                              return <Descriptions.Item key={item.key} label={item.title}
                                                        span={1}> 停止</Descriptions.Item>
                            }
                            if (microMotorlastData.parameters && microMotorlastData.parameters[item.key] && item.key === 'pos') {
                              if (microMotorlastData.parameters[item.key] === 'ABNORMAL') {
                                return <Descriptions.Item key={item.key} label={item.title}
                                                          span={1}> 异常</Descriptions.Item>
                              }
                              if (microMotorlastData.parameters[item.key] === 'CLOSED') {
                                return <Descriptions.Item key={item.key} label={item.title}
                                                          span={1}> 关闭</Descriptions.Item>
                              }
                              if (microMotorlastData.parameters[item.key] === 'OPENED') {
                                return <Descriptions.Item key={item.key} label={item.title}
                                                          span={1}> 打开</Descriptions.Item>
                              }
                              if (microMotorlastData.parameters[item.key] === 'UNKNOWN') {
                                return <Descriptions.Item key={item.key} label={item.title}
                                                          span={1}> 未知</Descriptions.Item>
                              }
                              return <Descriptions.Item key={item.key} label={item.title}
                                                        span={1}> 异常</Descriptions.Item>
                            }
                            if (microMotorlastData.parameters && microMotorlastData.parameters[item.key] && item.key === 'state') {
                              if (microMotorlastData.parameters[item.key] === 'MOVE') {
                                return <Descriptions.Item key={item.key} label={item.title}
                                                          span={1}> 移动</Descriptions.Item>
                              }
                              if (microMotorlastData.parameters[item.key] === 'STOP') {
                                return <Descriptions.Item key={item.key} label={item.title}
                                                          span={1}> 停止</Descriptions.Item>
                              }
                              if (microMotorlastData.parameters[item.key] === 'JAM') {
                                return <Descriptions.Item key={item.key} label={item.title}
                                                          span={1}> 阻塞</Descriptions.Item>
                              }
                              if (microMotorlastData.parameters[item.key] === 'FAULT') {
                                return <Descriptions.Item key={item.key} label={item.title}
                                                          span={1}> 故障</Descriptions.Item>
                              }
                              return <Descriptions.Item key={item.key} label={item.title}
                                                        span={1}> 移动</Descriptions.Item>
                            }
                            return ''
                          })}
                        </Descriptions>
                      </TabPane>
                    }
                    {
                      detail.row.template === 43 &&
                      <TabPane forceRender={true} tab={
                        <span>
                       水力发电管理
                      </span>
                      }
                               key={"61"}>
                        <Descriptions column={4} title={''} bordered>
                          <Descriptions.Item label="上传时间" span={4}> <Tooltip
                            title={pmslastData.collected_at}><span
                            style={{color: 'blue'}}>{pmslastData.collected_at}</span></Tooltip></Descriptions.Item>
                          <Descriptions.Item label="DC-DC输入电压(mV)" span={2}> <Tooltip
                            title={pmslastData.parameters ?
                              pmslastData.parameters.volt : ''}>{pmslastData.parameters ?
                            pmslastData.parameters.volt : ''}</Tooltip></Descriptions.Item>
                          <Descriptions.Item label="DC-DC输入电流(mA)" span={2}> <Tooltip
                            title={pmslastData.parameters ?
                              pmslastData.parameters.current : ''}>{pmslastData.parameters ?
                            pmslastData.parameters.current : ''}</Tooltip></Descriptions.Item>
                        </Descriptions>

                        <Descriptions column={4} title={''} bordered style={{marginTop: '20px'}}>
                          {[{title: "电池/电容并联电压基准(mV)", key: 'vshunt'},
                            {title: "输出电压欠压阈值(mV)", key: 'voutUvLvl'},
                            {title: "输出电压过压阈值(mV)", key: 'voutOvLvl'},
                            {title: "电池/电容组数量(组)", key: 'numCaps'},
                            {title: "充电状态\n", key: 'chrgStatus'},
                            {title: "监测状态\n", key: 'monStatus'},
                          ].map((item, index) => {
                            if (item.key === 'chrgStatus') {
                              if (pmslastData.parameters&&pmslastData.parameters.bms) {
                                return <Descriptions.Item key={item.key} label={item.title} span={1}>
                                  {padStart(that.hexToBinary(pmslastData.parameters.bms[item.key]), 16, 0).match(/.{1,4}/g).join(' ')}
                                  <Popover
                                    content={<div>
                                      <p> BIT(S) BIT NAME DESCRIPTION</p>
                                      0 chrg_stepdown The synchronous controller is in step-down mode (charging) <br/>
                                      1 chrg_stepup The synchronous controller is in step-up mode (backup) <br/>
                                      2 chrg_cv The charger is in constant voltage mode <br/>
                                      3 chrg_uvlo The charger is in undervoltage lockout <br/>
                                      4 chrg_input_ilim The charger is in input current limit <br/>
                                      5 chrg_cappg The capacitor voltage is above power good threshold <br/>
                                      6 chrg_shnt The capacitor manager is shunting <br/>
                                      7 chrg_bal The capacitor manager is balancing <br/>
                                      8 chrg_dis The charger is temporarily disabled for capacitance measurement <br/>
                                      9 chrg_ci The charger is in constant current mode <br/>
                                      10 – Reserved <br/>
                                      11 chrg_pfo Input voltage is below PFI threshold</div>
                                    }> <AIcon style={{
                                    fontSize: '16px', position: 'relative', color: 'blue', marginRight: '5px',
                                    top: '2px'
                                  }} type="question-circle"/></Popover>

                                </Descriptions.Item>

                              }
                            }
                            if (item.key === 'monStatus') {
                              if (pmslastData.parameters&&pmslastData.parameters.bms) {
                                return <Descriptions.Item key={item.key} label={item.title} span={1}>
                                  {padStart(that.hexToBinary(pmslastData.parameters.bms[item.key]), 16, 0).match(/.{1,4}/g).join(' ')}
                                  <Popover
                                    content={<div>
                                      <p> BIT(S) BIT NAME DESCRIPTION</p>
                                      0 mon_capesr_active Capacitance/ESR measurement is in progress <br/>
                                      1 mon_capesr_scheduled Waiting programmed time to begin a capacitance/ESR
                                      measurement <br/>
                                      2 mon_capesr_pending Waiting for satisfactory conditions to begin a
                                      capacitance/ESR
                                      measurement <br/>
                                      3 mon_cap_done Capacitance measurement has completed <br/>
                                      4 mon_esr_done ESR Measurement has completed <br/>
                                      5 mon_cap_failed The last attempted capacitance measurement was unable to
                                      complete <br/>
                                      6 mon_esr_failed The last attempted ESR measurement was unable to complete <br/>
                                      7 – Reserved <br/>
                                      8 mon_power_failed This bit is set when VIN falls below the PFI threshold or the
                                      charger is unable to <br/>
                                      charge. It is cleared only when power returns and the charger is able to
                                      charge. <br/>
                                      9 mon_power_returned This bit is set when the input is above the PFI threshold and
                                      the charger is able to <br/>
                                      charge. It is cleared only when mon_power_failed is set.</div>
                                    }> <AIcon style={{
                                    fontSize: '16px', position: 'relative', color: 'blue', marginRight: '5px',
                                    top: '2px'
                                  }} type="question-circle"/></Popover>

                                </Descriptions.Item>

                              }
                            }
                            return <Descriptions.Item key={item.key} label={item.title}
                                                      span={1}>  {(pmslastData.parameters&&pmslastData.parameters.bms) ?
                              pmslastData.parameters.bms[item.key] : ''}</Descriptions.Item>
                          })}
                          {[{title: "电池/电容1电压(mV)", key: 'measVcap1'},
                            {title: "电池/电容2电压(mV)", key: 'measVcap2'},
                            {title: "电池/电容3电压(mV)", key: 'measVcap3'},
                            {title: "电池/电容4电压(mV)", key: 'measVcap4'},
                            {title: "输入电压(mV)", key: 'measVin'},
                            {title: "电池/电容包电压(mV)", key: 'measVcap'},
                            {title: "输出电压(mV)", key: 'measVout'},
                            {title: "输入电流(mA)", key: 'measIin'},
                            {title: "充电电流(mA)", key: 'measIchg'},
                            {title: "芯片温度(°C)", key: 'measDetmp'}].map((item, index) => {
                            return <Descriptions.Item key={item.key} label={item.title}
                                                      span={1}>{(pmslastData.parameters&&pmslastData.parameters.bms) ?
                              pmslastData.parameters.bms[item.key] : ''}</Descriptions.Item>
                          })}
                        </Descriptions>
                        <Descriptions column={4} title={''} bordered style={{marginTop: '20px'}}>
                          {[{title: "电池/电容状态\n", key: 'capgd'},
                            {title: "BMS输出故障\n", key: 'pfo'},
                            {title: "BMS报警\n", key: 'smbalert'},
                            {title: "DC-DC电源状态\n", key: 'pgood'},
                            {title: "DC-DC工作模式\n", key: 'mode'},
                            {title: "DC-DC电流\n", key: 'ilim'},
                            {title: "DC-DC使能\n", key: 'ena'},
                            {title: "DC-DC输入监测报警\n", key: 'alert'},
                          ].map((item, index) => {
                            if (item.key === 'capgd') {
                              if (pmslastData.parameters&&pmslastData.parameters.bms) {
                                return <Descriptions.Item key={item.key} label={item.title} span={1}>
                                  {pmslastData.parameters.bms[item.key] ? '好' : '低于90%'}</Descriptions.Item>
                              }
                            }
                            if (item.key === 'pfo') {
                              if (pmslastData.parameters&&pmslastData.parameters.bms) {
                                return <Descriptions.Item key={item.key} label={item.title} span={1}>
                                  {pmslastData.parameters.bms[item.key]  ? '正常' : '异常'}</Descriptions.Item>
                              }
                            }
                            if (item.key === 'smbalert') {
                              if (pmslastData.parameters&&pmslastData.parameters.bms) {
                                return <Descriptions.Item key={item.key} label={item.title} span={1}>
                                  {pmslastData.parameters.bms[item.key]  ? '报警' : '无报警'}</Descriptions.Item>
                              }
                            }
                            if (item.key === 'pgood') {
                              if (pmslastData.parameters&&pmslastData.parameters.pwr) {
                                return <Descriptions.Item key={item.key} label={item.title} span={1}>
                                  {pmslastData.parameters.pwr[item.key]  ? '正常' : '异常'}</Descriptions.Item>
                              }
                            }
                            if (item.key === 'mode') {
                              if (pmslastData.parameters&&pmslastData.parameters.pwr) {
                                return <Descriptions.Item key={item.key} label={item.title} span={1}>
                                  {pmslastData.parameters.pwr[item.key]  ? 'automatic Burst Mode' : 'Fixed frequency PWM mode'}</Descriptions.Item>
                              }
                            }
                            if (item.key === 'ilim') {
                              if (pmslastData.parameters&&pmslastData.parameters.pwr) {
                                return <Descriptions.Item key={item.key} label={item.title} span={1}>
                                  {pmslastData.parameters.pwr[item.key]  ? '660mA' : '250mA'}</Descriptions.Item>
                              }
                            }
                            if (item.key === 'ena') {
                              if (pmslastData.parameters&&pmslastData.parameters.pwr) {
                                return <Descriptions.Item key={item.key} label={item.title} span={1}>
                                  {pmslastData.parameters.pwr[item.key]  ? '异常' : '正常'}</Descriptions.Item>
                              }
                            }
                            if (item.key === 'alert') {
                              if (pmslastData.parameters&&pmslastData.parameters.pwr) {
                                return <Descriptions.Item key={item.key} label={item.title} span={1}>
                                  {pmslastData.parameters.pwr[item.key]  ? 'Enable' : 'Disable'}</Descriptions.Item>
                              }
                            }
                            return <Descriptions.Item key={item.key} label={item.title}
                                                      span={1}> {pmslastData.parameters ?
                              pmslastData.parameters[item.key] : ''}</Descriptions.Item>
                          })}
                        </Descriptions>
                        <Descriptions column={4} title={''} bordered style={{marginTop: '20px'}}>
                          {[{title: "电源通道1/2状态\n\n", key: 'st12'},
                            {title: "电源通道3/4状态\n\n", key: 'st34'},
                            {title: "电源通道-1开关\n\n", key: 'sw1'},
                            {title: "电源通道-2开关\n\n", key: 'sw2'},
                            {title: "电源通道-3开关\n\n", key: 'sw3'},
                            {title: "电源通道-4开关\n\n", key: 'sw4'},
                            {title: "5v电源通道开关", key: 'v5'},
                          ].map((item, index) => {
                            let title = '';
                            if (item.key.indexOf('st') >= 0 && pmslastData.parameters&&pmslastData.parameters.output) {
                              if (pmslastData.parameters.output[item.key] == 0) {
                                title = '异常'
                              }
                              if (pmslastData.parameters.output[item.key] == 1) {
                                title = '正常'
                              }
                            }
                            if (item.key.indexOf('sw') >= 0 && pmslastData.parameters&&pmslastData.parameters.output) {
                              if (pmslastData.parameters.output[item.key] == 0) {
                                title = '关'
                              }
                              if (pmslastData.parameters.output[item.key] == 1) {
                                title = '开'
                              }
                            }
                            if (item.key.indexOf('v5') >= 0 && pmslastData.parameters&&pmslastData.parameters.output) {
                              if (pmslastData.parameters.output[item.key] == 0) {
                                title = '关'
                              }
                              if (pmslastData.parameters.output[item.key] == 1) {
                                title = '开'
                              }
                            }
                            return <Descriptions.Item key={item.key} label={item.title}
                                                      span={item.key.indexOf('st') >= 0 ? 2 : 1}> {title}</Descriptions.Item>
                          })}
                        </Descriptions>
                      </TabPane>
                    }
                  </Tabs>

                </TabPane>
              }
              {
                (detail.row.template === 41 || detail.row.template === 40 || detail.row.template === 43) &&
                <TabPane forceRender={true} tab="历史压力对比" key={"7"}
                         style={{overflowY: 'scroll', height: 'calc(100vh - 230px)'}}>
                  <div style={{position: 'relative', overflow: 'hidden'}}>

                    {
                      loading && <Loading/>
                    }
                    <div style={{marginBottom: '10px'}}>
                      <DatePicker
                        value={this.state.rangePickerValue_contrast[0]}
                        allowClear={false}
                        format="YYYY-MM-DD"
                        style={{width: 150}}
                        placeholder={'开始日期'}
                        onChange={(e) => this.handleRangePickerContrast(e, 'start')}
                      />
                      <DatePicker
                        allowClear={false}
                        value={this.state.rangePickerValue_contrast[1]}
                        format="YYYY-MM-DD"
                        placeholder={'结束日期'}
                        style={{width: 150}}
                        onChange={(e) => this.handleRangePickerContrast(e, 'end')}
                      />
                      <Button onClick={() => this.fetchDataSequentially()} type={'primary'}>获取</Button>

                    </div>
                    <div key={this.state.key}>
                      <div><ReactEcharts
                        option={this.getContrastOption('faqian')}
                        style={{height: 300, width: '100%'}}
                        theme='my_theme'
                        key={this.state.key+'faqian'}
                        //onChartReady={this.onChartReadyCallback}
                        //onEvents={EventsDict}
                      />
                      </div>
                      <div><ReactEcharts
                        option={this.getContrastOption('fahou')}
                        style={{height: 300, width: '100%'}}
                        theme='my_theme'
                        key={this.state.key+'faqian'}
                        //onChartReady={this.onChartReadyCallback}
                        //onEvents={EventsDict}
                      />
                      </div>
                    </div>

                  </div>

                </TabPane>
              }
              {
                detail.row.template === 4 &&
                <TabPane forceRender={true} tab="最新数据" key={"2"}>
                  <Descriptions column={4} title={''} bordered>
                    <Descriptions.Item label="上传时间" span={4}> <Tooltip
                      title={lastData.collected_at}><span
                      style={{color: 'blue'}}>{lastData.collected_at}</span></Tooltip></Descriptions.Item>
                    <Descriptions.Item label="DC-DC输入电压(mV)" span={2}> <Tooltip
                      title={lastData.parameters ?
                        lastData.parameters.VOLT : ''}>{lastData.parameters ?
                      lastData.parameters.VOLT : ''}</Tooltip></Descriptions.Item>
                    <Descriptions.Item label="DC-DC输入电流(mA)" span={2}> <Tooltip
                      title={lastData.parameters ?
                        lastData.parameters.CURRENT : ''}>{lastData.parameters ?
                      lastData.parameters.CURRENT : ''}</Tooltip></Descriptions.Item>
                  </Descriptions>

                  <Descriptions column={4} title={''} bordered style={{marginTop: '20px'}}>
                    {[{title: "电池/电容并联电压基准(mV)", key: 'vshunt'},
                      {title: "输出电压欠压阈值(mV)", key: 'voutUvLvl'},
                      {title: "输出电压过压阈值(mV)", key: 'voutOvLvl'},
                      {title: "电池/电容组数量(组)", key: 'numCaps'},
                      {title: "充电状态\n", key: 'chrgStatus'},
                      {title: "监测状态\n", key: 'monStatus'},
                    ].map((item, index) => {
                      if (item.key === 'CHRG_STATUS') {
                        if (lastData.parameters) {
                          return <Descriptions.Item key={item.key} label={item.title} span={1}>
                            {padStart(that.hexToBinary(lastData.parameters[item.key]), 16, 0).match(/.{1,4}/g).join(' ')}
                            <Popover
                              content={<div>
                                <p> BIT(S) BIT NAME DESCRIPTION</p>
                                0 chrg_stepdown The synchronous controller is in step-down mode (charging) <br/>
                                1 chrg_stepup The synchronous controller is in step-up mode (backup) <br/>
                                2 chrg_cv The charger is in constant voltage mode <br/>
                                3 chrg_uvlo The charger is in undervoltage lockout <br/>
                                4 chrg_input_ilim The charger is in input current limit <br/>
                                5 chrg_cappg The capacitor voltage is above power good threshold <br/>
                                6 chrg_shnt The capacitor manager is shunting <br/>
                                7 chrg_bal The capacitor manager is balancing <br/>
                                8 chrg_dis The charger is temporarily disabled for capacitance measurement <br/>
                                9 chrg_ci The charger is in constant current mode <br/>
                                10 – Reserved <br/>
                                11 chrg_pfo Input voltage is below PFI threshold</div>
                              }> <AIcon style={{
                              fontSize: '16px', position: 'relative', color: 'blue', marginRight: '5px',
                              top: '2px'
                            }} type="question-circle"/></Popover>

                          </Descriptions.Item>

                        }
                      }
                      if (item.key === 'MON_STATUS') {
                        if (lastData.parameters) {
                          return <Descriptions.Item key={item.key} label={item.title} span={1}>
                            {padStart(that.hexToBinary(lastData.parameters[item.key]), 16, 0).match(/.{1,4}/g).join(' ')}
                            <Popover
                              content={<div>
                                <p> BIT(S) BIT NAME DESCRIPTION</p>
                                0 mon_capesr_active Capacitance/ESR measurement is in progress <br/>
                                1 mon_capesr_scheduled Waiting programmed time to begin a capacitance/ESR
                                measurement <br/>
                                2 mon_capesr_pending Waiting for satisfactory conditions to begin a capacitance/ESR
                                measurement <br/>
                                3 mon_cap_done Capacitance measurement has completed <br/>
                                4 mon_esr_done ESR Measurement has completed <br/>
                                5 mon_cap_failed The last attempted capacitance measurement was unable to complete <br/>
                                6 mon_esr_failed The last attempted ESR measurement was unable to complete <br/>
                                7 – Reserved <br/>
                                8 mon_power_failed This bit is set when VIN falls below the PFI threshold or the charger
                                is unable to <br/>
                                charge. It is cleared only when power returns and the charger is able to charge. <br/>
                                9 mon_power_returned This bit is set when the input is above the PFI threshold and the
                                charger is able to <br/>
                                charge. It is cleared only when mon_power_failed is set.</div>
                              }> <AIcon style={{
                              fontSize: '16px', position: 'relative', color: 'blue', marginRight: '5px',
                              top: '2px'
                            }} type="question-circle"/></Popover>

                          </Descriptions.Item>

                        }
                      }
                      return <Descriptions.Item key={item.key} label={item.title}
                                                span={1}>  {(pmslastData.parameters&&pmslastData.parameters.bms) ?
                        pmslastData.parameters.bms[item.key] : ''}</Descriptions.Item>
                    })}
                    {[{title: "电池/电容1电压(mV)", key: 'measVcap1'},
                      {title: "电池/电容2电压(mV)", key: 'measVcap2'},
                      {title: "电池/电容3电压(mV)", key: 'measVcap3'},
                      {title: "电池/电容4电压(mV)", key: 'measVcap4'},
                      {title: "输入电压(mV)", key: 'measVin'},
                      {title: "电池/电容包电压(mV)", key: 'measVcap'},
                      {title: "输出电压(mV)", key: 'measVout'},
                      {title: "输入电流(mA)", key: 'measIin'},
                      {title: "充电电流(mA)", key: 'measIchg'},
                      {title: "芯片温度(°C)", key: 'measDetmp'}].map((item, index) => {
                      return <Descriptions.Item key={item.key} label={item.title}
                                                span={1}>{(pmslastData.parameters&&pmslastData.parameters.bms) ?
                        pmslastData.parameters.bms[item.key] : ''}</Descriptions.Item>
                    })}
                  </Descriptions>
                  <Descriptions column={4} title={''} bordered style={{marginTop: '20px'}}>
                    {[{title: "电池/电容状态\n", key: 'capgd'},
                      {title: "BMS输出故障\n", key: 'pfo'},
                      {title: "BMS报警\n", key: 'smbalert'},
                      {title: "DC-DC电源状态\n", key: 'pgood'},
                      {title: "DC-DC工作模式\n", key: 'mode'},
                      {title: "DC-DC电流\n", key: 'ilim'},
                      {title: "DC-DC使能\n", key: 'ena'},
                      {title: "DC-DC输入监测报警\n", key: 'alert'},
                    ].map((item, index) => {
                      if (item.key === 'capgd') {
                        if (pmslastData.parameters&&pmslastData.parameters.bms) {
                          return <Descriptions.Item key={item.key} label={item.title} span={1}>
                            {pmslastData.parameters.bms[item.key] ? '好' : '低于90%'}</Descriptions.Item>
                        }
                      }
                      if (item.key === 'pfo') {
                        if (pmslastData.parameters&&pmslastData.parameters.bms) {
                          return <Descriptions.Item key={item.key} label={item.title} span={1}>
                            {pmslastData.parameters.bms[item.key]  ? '正常' : '异常'}</Descriptions.Item>
                        }
                      }
                      if (item.key === 'smbalert') {
                        if (pmslastData.parameters&&pmslastData.parameters.bms) {
                          return <Descriptions.Item key={item.key} label={item.title} span={1}>
                            {pmslastData.parameters.bms[item.key]  ? '报警' : '无报警'}</Descriptions.Item>
                        }
                      }
                      if (item.key === 'pgood') {
                        if (pmslastData.parameters&&pmslastData.parameters.bms) {
                          return <Descriptions.Item key={item.key} label={item.title} span={1}>
                            {pmslastData.parameters.pwr[item.key]  ? '正常' : '异常'}</Descriptions.Item>
                        }
                      }
                      if (item.key === 'mode') {
                        if (pmslastData.parameters&&pmslastData.parameters.pwr) {
                          return <Descriptions.Item key={item.key} label={item.title} span={1}>
                            {pmslastData.parameters.pwr[item.key]  ? 'automatic Burst Mode' : 'Fixed frequency PWM mode'}</Descriptions.Item>
                        }
                      }
                      if (item.key === 'ilim') {
                        if (pmslastData.parameters&&pmslastData.parameters.pwr) {
                          return <Descriptions.Item key={item.key} label={item.title} span={1}>
                            {pmslastData.parameters.pwr[item.key]  ? '660mA' : '250mA'}</Descriptions.Item>
                        }
                      }
                      if (item.key === 'ena') {
                        if (pmslastData.parameters&&pmslastData.parameters.pwr) {
                          return <Descriptions.Item key={item.key} label={item.title} span={1}>
                            {pmslastData.parameters.pwr[item.key]  ? '异常' : '正常'}</Descriptions.Item>
                        }
                      }
                      if (item.key === 'alert') {
                        if (pmslastData.parameters&&pmslastData.parameters.pwr) {
                          return <Descriptions.Item key={item.key} label={item.title} span={1}>
                            {pmslastData.parameters.pwr[item.key]  ? 'Enable' : 'Disable'}</Descriptions.Item>
                        }
                      }
                      return <Descriptions.Item key={item.key} label={item.title}
                                                span={1}> {pmslastData.parameters ?
                        pmslastData.parameters[item.key] : ''}</Descriptions.Item>
                    })}
                  </Descriptions>
                  <Descriptions column={4} title={''} bordered style={{marginTop: '20px'}}>
                    {[{title: "电源通道1/2状态\n\n", key: 'st12'},
                      {title: "电源通道3/4状态\n\n", key: 'st34'},
                      {title: "电源通道-1开关\n\n", key: 'sw1'},
                      {title: "电源通道-2开关\n\n", key: 'sw2'},
                      {title: "电源通道-3开关\n\n", key: 'sw3'},
                      {title: "电源通道-4开关\n\n", key: 'sw4'},
                      {title: "5v电源通道开关", key: 'v5'},
                    ].map((item, index) => {
                      let title = '';
                      if (item.key.indexOf('st') >= 0 && pmslastData.parameters&&pmslastData.parameters.output) {
                        if (pmslastData.parameters.output[item.key] == 0) {
                          title = '异常'
                        }
                        if (pmslastData.parameters.output[item.key] == 1) {
                          title = '正常'
                        }
                      }
                      if (item.key.indexOf('sw') >= 0 && pmslastData.parameters&&pmslastData.parameters.output) {
                        if (pmslastData.parameters.output[item.key] == 0) {
                          title = '关'
                        }
                        if (pmslastData.parameters.output[item.key] == 1) {
                          title = '开'
                        }
                      }
                      if (item.key.indexOf('v5') >= 0 && pmslastData.parameters&&pmslastData.parameters.output) {
                        if (pmslastData.parameters.output[item.key] == 0) {
                          title = '关'
                        }
                        if (pmslastData.parameters.output[item.key] == 1) {
                          title = '开'
                        }
                      }
                      return <Descriptions.Item key={item.key} label={item.title}
                                                span={item.key.indexOf('st') >= 0 ? 2 : 1}> {title}</Descriptions.Item>
                    })}
                  </Descriptions>
                </TabPane>
              }
              {/*   {
                detail.row.template===1&&
                <TabPane forceRender={true} tab="3D模型" key={"2"}>
                  <iframe id={'RTU_iframe'} src="https://www.thingjs.com/pp/2ac381671a830e47855003f1" style={{
                    width: '100%',
                    height: 'calc(100vh - 230px)', border: 'none'
                  }}></iframe>
                </TabPane>
              } */}
              <TabPane tab="下发日志" key={"3"}>
                <div>
                  <ButtonGroup>
                    <Button onClick={() => this.selectDate2('month')}
                            type={this.isActive2('month') ? 'primary' : ''}>本月</Button>
                    <Button onClick={() => this.selectDate2('year')}
                            type={this.isActive2('year') ? 'primary' : ''}>本年</Button>
                  </ButtonGroup>

                  <DatePicker
                    value={this.state.rangePickerValue2[0]}
                    allowClear={false}
                    format="YYYY-MM-DD"
                    style={{width: 150}}
                    placeholder={'开始日期'}
                    onChange={(e) => this.handleRangePickerChange2(e, 'start')}
                  />
                  <DatePicker
                    allowClear={false}
                    value={this.state.rangePickerValue2[1]}
                    format="YYYY-MM-DD"
                    placeholder={'结束日期'}
                    style={{width: 150}}
                    onChange={(e) => this.handleRangePickerChange2(e, 'end')}
                  />

                  {/*  {
                    detail.row.template === 1 &&
                    <Button
                      type="primary"
                      className={'btn-green'}
                      icon="setting"
                      style={{marginLeft: '12px'}}
                      onClick={(e) => {
                        this.setState({
                          configModal: true,
                        });
                      }
                      }
                    >下发指令
                    </Button>
                  } */}
                </div>
                <div style={{height: '450px', marginTop: '10px', position: 'relative'}}>
                  {
                    loading2 && <Loading/>
                  }
                  <ReactDataGrid
                    columns={columns2}
                    rowGetter={i => reverceData2[i]}
                    rowsCount={reverceData2.length}
                    minHeight={530}
                    headerRowHeight={35}
                    rowHeight={40}
                  />

                </div>
              </TabPane>
              <TabPane tab="上传日志" key={"4"}>
                {
                  (detail.row.template === 41 || detail.row.template === 40 || detail.row.template === 43) &&
                  <div style={{position: 'relative'}}>
                    <div style={{marginBottom: '10px'}}>
                      <Select style={{width:'120px'}} onChange={(value)=>{
                        this.fetch({
                          ...this.state.searchParams,
                          page: 1,
                          showType:value
                        })
                      }} value={this.state.searchParams.showType}>
                        {/*<Option value={''}>全部</Option>*/}
                        <Option value={''}>全部</Option>
                        <Option value={(detail.row.template === 40)?'rtu03p_hw_info':'rtu04p_hw_info'}>硬件信息</Option>
                        <Option value={(detail.row.template === 40)?'rtu03p_runtime':'rtu04p_runtime'}>运行状态</Option>
                        <Option value={(detail.row.template === 40)?'rtu03p_record':'rtu04p_record'}>采集信息</Option>
                      </Select>
                      <ButtonGroup>
                        <Button onClick={() => this.selectDate('month')}
                                type={this.isActive('month') ? 'primary' : ''}>本月</Button>
                        <Button onClick={() => this.selectDate('year')}
                                type={this.isActive('year') ? 'primary' : ''}>本年</Button>
                      </ButtonGroup>

                      <DatePicker
                        value={this.state.rangePickerValue[0]}
                        allowClear={false}
                        format="YYYY-MM-DD"
                        style={{width: 150}}
                        placeholder={'开始日期'}
                        onChange={(e) => this.handleRangePickerChange(e, 'start')}
                      />
                      <DatePicker
                        allowClear={false}
                        value={this.state.rangePickerValue[1]}
                        format="YYYY-MM-DD"
                        placeholder={'结束日期'}
                        style={{width: 150}}
                        onChange={(e) => this.handleRangePickerChange(e, 'end')}
                      />
                      <Button onClick={() => this.fetch({
                        ...this.state.searchParams,
                        page: 1,
                      })} type={'primary'}>刷新</Button>

                      <Button type={'primary'} style={{ marginLeft: '10px' }} onClick={() => {
                        this.props.downloadHistory(moment(this.state.rangePickerValue[0]).format('YYYY-MM-DD'),moment(this.state.rangePickerValue[1]).format('YYYY-MM-DD'), this.props.editRecord.id);

                      }}>下载当前时间段数据</Button>

                    </div>
                    {
                      loading && <Loading/>
                    }
                    <ReactDataGrid
                      columns={columns}
                      rowGetter={i => reverceData[i]}
                      rowsCount={reverceData.length}
                      minHeight={490}
                      headerRowHeight={35}
                      rowHeight={40}
                    />
                    <div style={{marginTop: '10px'}}>
                      <MyPagination searchCondition={{...this.state.searchParams}} meta={meta}
                                    handleSearch={this.fetch}/>

                    </div>
                  </div>
                }
                {
                  detail.row.template === 4 &&
                  <div style={{position: 'relative'}}>
                    <div style={{marginBottom: '10px'}}>
                      <ButtonGroup>
                        <Button onClick={() => this.selectDate('month')}
                                type={this.isActive('month') ? 'primary' : ''}>本月</Button>
                        <Button onClick={() => this.selectDate('year')}
                                type={this.isActive('year') ? 'primary' : ''}>本年</Button>
                      </ButtonGroup>

                      <DatePicker
                        value={this.state.rangePickerValue[0]}
                        allowClear={false}
                        format="YYYY-MM-DD"
                        style={{width: 150}}
                        placeholder={'开始日期'}
                        onChange={(e) => this.handleRangePickerChange(e, 'start')}
                      />
                      <DatePicker
                        allowClear={false}
                        value={this.state.rangePickerValue[1]}
                        format="YYYY-MM-DD"
                        placeholder={'结束日期'}
                        style={{width: 150}}
                        onChange={(e) => this.handleRangePickerChange(e, 'end')}
                      />
                      <Button onClick={() => this.fetch({
                        ...this.state.searchParams,
                        page: 1,
                      })} type={'primary'}>刷新</Button>

                    </div>
                    {
                      loading && <Loading/>
                    }
                    <ReactDataGrid
                      columns={columns}
                      rowGetter={i => reverceData[i]}
                      rowsCount={reverceData.length}
                      minHeight={490}
                      headerRowHeight={35}
                      rowHeight={40}
                    />
                    <div style={{marginTop: '10px'}}>
                      <MyPagination searchCondition={{...this.state.searchParams}} meta={meta}
                                    handleSearch={this.fetch}/>

                    </div>
                  </div>
                }
              </TabPane>
              {/*  {
                detail.row.template === 1 &&
                <TabPane tab="压力曲线" key={"5"}>
                  <div style={{position: 'relative'}}>

                    {
                      loading && <Loading/>
                    }
                    <div style={{marginBottom: '10px'}}>
                      <ButtonGroup>
                        <Button onClick={() => this.selectDateControlLine('month')}
                                type={this.isActiveLine('month') ? 'primary' : ''}>本月</Button>
                        <Button onClick={() => this.selectDateControlLine('year')}
                                type={this.isActiveLine('year') ? 'primary' : ''}>本年</Button>
                      </ButtonGroup>

                      <DatePicker
                        value={this.state.rangePickerValue_control_line[0]}
                        allowClear={false}
                        format="YYYY-MM-DD"
                        style={{width: 150}}
                        placeholder={'开始日期'}
                        onChange={(e) => this.handleRangePickerChangeControlLine(e, 'start')}
                      />
                      <DatePicker
                        allowClear={false}
                        value={this.state.rangePickerValue_control_line[1]}
                        format="YYYY-MM-DD"
                        placeholder={'结束日期'}
                        style={{width: 150}}
                        onChange={(e) => this.handleRangePickerChangeControlLine(e, 'end')}
                      />
                      <Button onClick={() => this.fetch_control_line({
                        ...this.state.searchParams_control_line,
                        page: 1,
                      })} type={'primary'}>刷新</Button>

                    </div>
                    <div><ReactEcharts
                      option={this.getOption()}
                      style={{height: document.body.offsetHeight - 310, width: '100%'}}
                      theme='my_theme'
                      //onChartReady={this.onChartReadyCallback}
                      //onEvents={EventsDict}
                    />
                    </div>
                    <div style={{marginTop: '10px'}}>
                      <MyPagination searchCondition={{...this.state.searchParams_control_line}}
                                    meta={this.state.meta_control_line} handleSearch={this.fetch_control_line}/>

                    </div>
                  </div>
                </TabPane>
              } */}
            </Tabs>

{/*            <Drawer
              title={`指令下发`}
              placement="right"
              closable={false}
              width={500}
              onClose={() => {
                this.setState({senDataModal: false})
              }}
              visible={this.state.senDataModal2}
            >
              <SendData detail={this.state.detail}/>
            </Drawer>
            <Modal
              title={<BuildModalTitle visible={this.state.senDataModal} modalClass="senDataModal"
                                      title={`指令下发`}/>}

              visible={this.state.senDataModal}
              centered
              className="senDataModal"
              afterClose={() => {
                afterCloseModal(); // destroyOnClose需要
              }}
              onCancel={() => {
                this.setState({senDataModal: false});
              }}
              onOk={this.sedData}


            >
              <SendData detail={this.state.detail} wrappedComponentRef={(inst) => this.SendDataForm = inst}/>

            </Modal>*/}
            <Modal
              title={<BuildModalTitle visible={this.state.infoModal} modalClass="infoModal"
                                      title={`查看详情`}/>}
              destroyOnClose
              visible={this.state.infoModal}
              centered
              className="infoModal"
              afterClose={() => {
                afterCloseModal(); // destroyOnClose需要
              }}
              onCancel={() => {
                this.setState({infoModal: false});
              }}
              footer={null}


            >
              <JSONData
                retry={this.state.retry}
                jsonData={this.state.jsonData}
                sedData2={this.sedData2}
                wrappedComponentRef={(inst) => this.sendDataForm2 = inst}
              />

            </Modal>
            <Modal
              title={<BuildModalTitle visible={this.state.initModal} modalClass="initModal"
                                      title={`初始化`}/>}
              destroyOnClose
              visible={this.state.initModal}
              centered
              className="initModal"
              afterClose={() => {
                afterCloseModal(); // destroyOnClose需要
              }}
              onCancel={() => {
                this.setState({initModal: false});
              }}
              width={600}
              onOk={this.initCommand}
            >
               <Init
                 template={detail.row.template}
                 wave={wave}
                 type={type}
                 range={range}
                 p0={p0}
                 p1={p1}
                 p2={p2}
                 p3={p3}
                 state_interval={interval}
                 record_interval={recordInterval}
                 delay={delay}
                wrappedComponentRef={(inst) => this.initForm = inst}
              />


            </Modal>
          </div>
        </div>
     {/*   <Modal
          title={<BuildModalTitle visible={this.state.configModal} modalClass="configModal"
                                  title={`下发指令`}/>}
          destroyOnClose
          visible={this.state.configModal}
          centered
          onOk={this.handleConfig}
          className="configModal"
          afterClose={() => {
            afterCloseModal(); // destroyOnClose需要
          }}
          onCancel={() => {
            this.setState({configModal: false, editRecord: {}});
          }}

        >
          <Config
            hardware_configs={detail.row.hardware_configs}
            editRecord={detail.row}
            wrappedComponentRef={(inst) => this.configForm = inst}
          />

        </Modal>*/}
    {/*    <Modal
          title={<BuildModalTitle visible={this.state.fadianjiModal} modalClass="fadianjiModal"
                                  title={`水力发电下发指令`}/>}
          destroyOnClose
          visible={this.state.fadianjiModal}
          centered
          onOk={this.handleConfig}
          className="fadianjiModal"
          afterClose={() => {
            afterCloseModal(); // destroyOnClose需要
          }}
          onCancel={() => {
            this.setState({fadianjiModal: false, editRecord: {}});
          }}

        >
          <Config
            hardware_configs={detail.row.hardware_configs}
            editRecord={detail.row}
            wrappedComponentRef={(inst) => this.configForm = inst}
          />

        </Modal>*/}
        <Modal
          title={<BuildModalTitle visible={this.state.diandaofaModal} modalClass="diandaofaModal"
                                  title={`智能电导阀下发指令`}/>}
          visible={this.state.diandaofaModal}
          centered
          onOk={this.handleConfig}
          className="diandaofaModal"
          width={750}
          onCancel={() => {
            this.setState({diandaofaModal: false, editRecord: {}});
          }}

        >
          <Config42
            hardware_configs={detail.row.hardware_configs}
            editRecord={detail.row}
            wrappedComponentRef={(inst) => this.configForm = inst}
          />

          {/* <RTUConfig
            hardware_configs={detail.row.hardware_configs}
            editRecord={detail.row}
            wrappedComponentRef={(inst) => this.RTUConfigForm = inst}
          /> */}
        </Modal>
      </div>

    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);
